<?php

namespace app\api\model;

use think\Model;

class Product extends BaseModel
{
    protected $hidden = [
        'update_time','delete_time','pivot','category_id','from','create_time'
    ];

    public function getMainImgUrlAttr($value, $data)
    {
        return $this->prefixImgUrl($value, $data);
    }
    public function imgs()
    {
        return $this->hasMany('ProductImage', 'product_id', 'id');
    }

    public function properties()
    {
        return $this->hasMany('ProductProperty', 'product_id', 'id');
    }

    public static function getMostRecent($count)
    {
        $products = self::limit($count)
                    ->order('create_time desc')
                    ->select();
        return $products;
    }

    public static function getProductsByCategoryID($categoryID)
    {
        $products = self::where('category_id', '=', $categoryID)->select();
        return $products;
    }

    public static function getProductDetail($id)
    {
        /**
         * with() 是链式方法
         * self::with(['imgs.imgUrl']) 可改写为 闭包写法
         * self::with(['imgs' => function($query){$query->with(['imgUrl'])}])
         */
        $product = self::with([
            'imgs' => function ($query) {
                $query->with(['imgUrl'])
                ->order('order asc');
            }
        ])
        ->with(['properties'])
        ->find($id);
        return $product;
    }
}
